package karileet.meeting.profile.list.adapter;

import java.util.List;

import karileet.meeting.profile.ProfileConf;
import karileet.meeting.profile.list.holder.ScheduleListItemHolder;
import karileet.meeting.profile.list.item.ScheduleListItem;

import karileet.meeting.profile.R;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class ScheduleListItemAdapter extends ArrayAdapter<ScheduleListItem> {

	  private final List<ScheduleListItem> list;
	  private final Activity context;

	  public ScheduleListItemAdapter(Activity context, List<ScheduleListItem> list) {
	    super(context, R.layout.schedule_list_item, list);
	    this.context = context;
	    this.list = list;
	  }
	  
	  
	  @Override
	  public View getView(int position, View convertView, ViewGroup parent) {
		  View view = null;
		  if (convertView == null) {
			  LayoutInflater inflator = context.getLayoutInflater();
		      view = inflator.inflate(R.layout.schedule_list_item, null);
			  final ScheduleListItemHolder ScheduleListItemHolder = new ScheduleListItemHolder();
			  
			  ScheduleListItemHolder.setTitle((TextView) view.findViewById(R.id.rowTitle));
			  ScheduleListItemHolder.setTime((TextView) view.findViewById(R.id.rowTime));
			  ScheduleListItemHolder.setDescription((TextView) view.findViewById(R.id.rowDescription));
			  CheckBox cb = (CheckBox) view.findViewById(R.id.rowActive);
			  cb.setChecked(list.get(position).isSelected());
			  ScheduleListItemHolder.setCb(cb);
			  view.setTag(ScheduleListItemHolder);
			  ScheduleListItemHolder.setTag(list.get(position));
		  } else {
			  view = convertView;
			  //something i do not understand is omitted
			  
		  }
		  
		  ScheduleListItemHolder holder = (ScheduleListItemHolder) view.getTag();
		  holder.setTitleText(list.get(position).getTitle());
		  holder.setTimeText(list.get(position).getTime());
		  holder.setDescriptionText(list.get(position).getDescription());
		  holder.check(list.get(position).isSelected());
		  final int pos = position;
		  final ProfileConf ps = new ProfileConf(getContext());
		  //toggle start and stop when checkbox is checked
		  holder.getCb().setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				list.get(pos).toggle();
				if (list.get(pos).getType() == 0) {
					Log.d(ProfileConf.APP, "Toggling scheduleStart");
					ps.setScheduleStartEnabled(list.get(pos).isSelected());
				} else {
					Log.d(ProfileConf.APP, "Toggling scheduleStop");
					ps.setScheduleStopEnabled(list.get(pos).isSelected());
				}
			}
		});
		  return view;
	  }
}
